
const express = require('express');
const router = express.Router();
const {User}  = require('../../models')
const {Op} = require('sequelize')
const jwt = require('jsonwebtoken')

router.post('/login', async function(req, res, next) {
    try {
        const body = {
            login: req.body.login,
            password: req.body.password
        }
        if(!body.login || !body.password) {
            res.status(500).json({
                status: false, 
                message: 'error',
                error: ['用户名或密码必须输入']
            })
        } else {
            const condition = {
                where: {
                    [Op.or]: [{
                        user_name: body.login
                    }]
                }
            }
            const user = await User.findOne(condition)
            if(!user) {
                res.status(404).json({
                    status: false, 
                    message: 'error',
                    error: ['用户不存在']
                })
            } else {
                if(user.password !== body.password) {
                    res.status(404).json({
                        status: false, 
                        message: 'error',
                        error: ['密码不正确']
                    })
                } else{
                    // 生成身份验证令牌
                    const token=jwt.sign({
                            userId:user.id
                        },
                        process.env.SECRET,
                        {expiresIn:'30d' }
                    );
                    res.status(201).json( {status: true, message: '创建文章成功', 
                        data: {
                            token
                        } });
                }
            }

    
            
            
            
        }
        
    } catch (error) {
        res.status(500).json({
            status: false, 
            message: 'error',
            error: [error.message]
        })
    }
    
});



module.exports = router;
